// 加载页逻辑

(function () {

    let loadedCount = 0;

    let isLoadingComplete = false;

    // 需要加载的图片列表

    const imageList = [

        './imgs/01.webp', './imgs/02.webp', './imgs/03.webp', './imgs/04.webp',

        './imgs/05.webp', './imgs/06.webp', './imgs/07.webp', './imgs/08.webp',

        './imgs/09.webp', './imgs/10.webp', './imgs/11.webp', './imgs/12.webp',

        './imgs/logo.webp', './imgs/mark.webp', './imgs/success.webp', './imgs/fail.webp'

    ];



    // 总资源数 = CSS + 音频 + 图片数量

    const totalResources = 2 + imageList.length;



    const $progress = $('.loading-progress');

    const $startBtn = $('.start-btn');

    const $loadingPage = $('.loading-page');

    const $loadingBar = $('.loading-bar');



    // 超时处理

    const loadingTimeout = setTimeout(() => {

        if (!isLoadingComplete) {

            console.log('加载超时');

            forceCompleteLoading();

        }

    }, 8000);



    // 强制完成加载

    function forceCompleteLoading() {

        if (isLoadingComplete) return;



        isLoadingComplete = true;

        clearTimeout(loadingTimeout);



        // 强制设置进度条为100%

        $progress.css('width', '100%');

        $('.loading-percentage').text('100%');



        // 延迟显示开始按钮

        setTimeout(() => {

            fadeOut($loadingBar.parent(), 300, () => {

                fadeIn($startBtn, 300);

            });

        }, 500);

    }



    // 淡入淡出函数

    function fadeOut($element, duration, callback) {

        $element.css({

            'opacity': 1,

            'transition': `opacity ${duration}ms`

        });

        setTimeout(() => {

            $element.css('opacity', 0);

            setTimeout(() => {

                $element.css('display', 'none');

                if (callback) callback();

            }, duration);

        }, 0);

    }



    function fadeIn($element, duration, callback) {

        $element.css({

            'opacity': 0,

            'display': 'block',

            'transition': `opacity ${duration}ms`

        });

        setTimeout(() => {

            $element.css('opacity', 1);

            if (callback) {

                setTimeout(callback, duration);

            }

        }, 0);

    }



    // 更新进度条和百分比

    function updateProgress() {

        if (isLoadingComplete) return;



        loadedCount++;

        const progress = (loadedCount / totalResources) * 100;

        const progressText = Math.round(progress) + '%';



        $progress.css('width', progress + '%');

        $('.loading-percentage').text(progressText);



        if (loadedCount === totalResources) {

            isLoadingComplete = true;

            clearTimeout(loadingTimeout);



            setTimeout(() => {

                fadeOut($loadingBar.parent(), 300, () => {

                    fadeIn($startBtn, 300);

                });

            }, 500);

        }

    }



    // 检查资源加载

    function checkResource(url, callback) {

        const isCSS = url.endsWith('.css');

        const isAudio = url.endsWith('.mp3');

        const isImage = /\.(webp)$/i.test(url);



        if (isCSS) {

            const link = document.createElement('link');

            link.onload = callback;

            link.rel = 'stylesheet';

            link.href = url;

            document.head.appendChild(link);

        } else if (isAudio) {

            const audio = new Audio();

            audio.oncanplaythrough = callback;

            audio.src = url;

        } else if (isImage) {

            const img = new Image();

            img.onload = callback;

            img.onerror = callback;

            img.src = url;

        }

    }



    checkResource('./style/index.css', updateProgress);

    checkResource('./audio/bgm01.mp3', updateProgress);



    imageList.forEach(imgUrl => {
        checkResource(imgUrl, updateProgress);

    });



    // 开始游戏按钮

    $startBtn.on('click', function () {
        fadeOut($loadingPage, 500);
    });

})();



// 卡牌数据

const cartData = [

    {

        id: 1,

        type: "sgj1",

        url: "./imgs/01.webp",

        audio: "./audio/sgj.mp3"

    },

    {

        id: 2,

        type: "sgj2",

        url: "./imgs/02.webp",

        audio: "./audio/sgj.mp3"

    },

    {

        id: 3,

        type: "sgj3",

        url: "./imgs/03.webp",

        audio: "./audio/sgj.mp3"

    },

    {

        id: 4,

        type: "sgj4",

        url: "./imgs/04.webp",

        audio: "./audio/sgj.mp3"

    },

    {

        id: 5,

        type: "sgj5",

        url: "./imgs/05.webp",

        audio: "./audio/sgj.mp3"

    },

    {

        id: 6,

        type: "sgj6",

        url: "./imgs/06.webp",

        audio: "./audio/sgj.mp3"

    },

    {

        id: 7,

        type: "dhdw1",

        url: "./imgs/07.webp",

        audio: "./audio/dhdw.mp3"

    },

    {

        id: 8,

        type: "dhdw2",

        url: "./imgs/08.webp",

        audio: "./audio/dhdw.mp3"

    },

    {

        id: 9,

        type: "dhdw3",

        url: "./imgs/09.webp",

        audio: "./audio/dhdw.mp3"

    },

    {

        id: 10,

        type: "dhdw4",

        url: "./imgs/10.webp",

        audio: "./audio/dhdw.mp3"

    },

    {

        id: 11,

        type: "dhdw5",

        url: "./imgs/11.webp",

        audio: "./audio/dhdw.mp3"

    },

    {

        id: 12,

        type: "dhdw6",

        url: "./imgs/12.webp",

        audio: "./audio/dhdw.mp3"

    },

]



const audioList = ['./audio/wow.mp3', './audio/oy.mp3']



function getCardTypeCount(level) {

    switch (level) {

        case 1:

            return 3;

        case 2:

            return 5;

        case 3:

            return 7;

        case 4:

            return 9;

        case 5:

        case 6:

            return 12;

        default:

            return 0;

    }

}



let currentLevel = 1;

let totalCards = 0;

let remainingCards = 0;

let storedCards = [];

let cardPositions = [];



function updateTime() {

    const now = new Date();

    const month = now.getMonth() + 1;

    const day = now.getDate();

    const hours = String(now.getHours()).padStart(2, '0');

    const minutes = String(now.getMinutes()).padStart(2, '0');

    const seconds = String(now.getSeconds()).padStart(2, '0');



    const dateStr = `${month}月${day}日`;

    const timeStr = `${hours}:${minutes}:${seconds}`;



    document.querySelector('.date').firstChild.textContent = dateStr;

    document.querySelector('.date .time').textContent = timeStr;

}

updateTime();

setInterval(updateTime, 1000);



function getRandomInt(min, max) {

    return Math.floor(Math.random() * (max - min + 1)) + min;

}



function createCard(level) {

    $('.cards-box').empty();

    storedCards = [];

    $('.stored-card .item').each(function () {

        $(this).children().not('i').remove();

    });



    const typeCount = getCardTypeCount(level);

    const selectedTypes = [];

    const availableTypes = [...cartData];



    // 随机选择卡牌类型

    for (let i = 0; i < typeCount; i++) {

        const randomIndex = getRandomInt(0, availableTypes.length - 1);

        selectedTypes.push(availableTypes[randomIndex]);

        availableTypes.splice(randomIndex, 1);

    }



    // 确定每种卡牌的数量

    const cardsPerType = level === 6 ? 9 : 6;

    const allCards = [];



    selectedTypes.forEach(card => {

        for (let i = 0; i < cardsPerType; i++) {

            allCards.push({ ...card });

        }

    });



    // 随机打乱卡牌

    for (let i = allCards.length - 1; i > 0; i--) {

        const j = Math.floor(Math.random() * (i + 1));

        [allCards[i], allCards[j]] = [allCards[j], allCards[i]];

    }



    // 保存卡牌总数和剩余卡牌数

    totalCards = allCards.length;

    remainingCards = totalCards;

    $('#card-count').text(remainingCards);

    $('.leftover').text(`还剩${remainingCards}张牌`);

    $('#match-progress').text('0%');



    // 生成卡牌位置

    const cardWidth = $('.stored-card .item').width();

    const cardHeight = $('.stored-card .item').height();

    generateCardPositions(allCards.length, cardWidth, cardHeight);



    // 创建卡牌元素

    allCards.forEach((cardData, index) => {

        const card = $('<div>').addClass('card').attr({

            'data-type': cardData.type,

            'data-id': cardData.id

        }).css({

            left: cardPositions[index].x + 'px',

            top: cardPositions[index].y + 'px',

            'z-index': cardPositions[index].z

        });



        const mask = $('<div>').addClass('mask');

        const img = $('<div>').addClass('img').css('background-image', `url(${cardData.url})`);



        card.append(mask, img);

        card.on('click', function () {

            if ($(this).hasClass('eliminate') || $(this).find('.mask').css('display') !== 'none') return;

            playSound(cardData.audio);

            moveToStoredArea($(this));

        });



        $('.cards-box').append(card);

    });



    // 更新关卡显示

    $('.game-levels').text(getLevelName(level));

    $('.level-indicator').text(getLevelName(level));



    // 更新mask显示状态

    updateCardMasks();

}



function generateCardPositions(cardCount, cardWidth, cardHeight) {

    cardPositions = [];

    const box = $('.cards-box')[0];

    const boxRect = box.getBoundingClientRect();

    const boxWidth = boxRect.width;

    const boxHeight = boxRect.height;



    if (cardWidth <= 0 || cardHeight <= 0) {

        cardWidth = 80;

        cardHeight = 100;

    }



    // 计算可用空间 

    const maxX = Math.max(0, boxWidth - cardWidth);

    const maxY = Math.max(0, boxHeight - cardHeight);



    if (maxX <= 0 || maxY <= 0) {

        console.error("卡片容器太小，无法放置卡片");

        // 创建默认位置

        for (let i = 0; i < cardCount; i++) {

            cardPositions.push({

                x: Math.max(0, (boxWidth - cardWidth) / 2),

                y: Math.max(0, (boxHeight - cardHeight) / 2),

                z: i + 1

            });

        }

        return;

    }



    // 计算最少需要的层数

    const minLayers = Math.ceil(cardCount / 15);

    const maxPossibleLayers = Math.ceil(cardCount / 4);

    const layers = getRandomInt(minLayers, maxPossibleLayers);



    // 确保每层至少有4张卡片的随机分配逻辑

    let remainingCards = cardCount;

    const cardsPerLayer = [];



    for (let i = 0; i < layers; i++) {

        cardsPerLayer.push(4);

        remainingCards -= 4;

    }



    // 随机分配剩余的卡片

    while (remainingCards > 0) {

        const randomLayer = getRandomInt(0, layers - 1);

        cardsPerLayer[randomLayer]++;

        remainingCards--;

    }



    // 垂直偏移参数

    const verticalOffsetRange = [cardHeight * 0.3, cardHeight * 0.5];

    const layerOffsets = [];

    for (let i = 0; i < layers; i++) {

        // 随机偏移量

        const offsetAmount = getRandomInt(

            Math.floor(verticalOffsetRange[0]),

            Math.ceil(verticalOffsetRange[1])

        );

        // 随机方向（1为向下，-1为向上）

        const direction = getRandomInt(0, 1) === 0 ? -1 : 1;

        layerOffsets.push(offsetAmount * direction);

    }



    for (let layer = 0; layer < layers; layer++) {

        const layerZIndex = layer + 1;

        const layerCards = cardsPerLayer[layer];



        // 计算当前层可以放置的网格行列数

        const maxCols = 6;

        const rows = Math.ceil(layerCards / maxCols);

        const cols = Math.min(maxCols, layerCards);

        // 计算网格单元尺寸

        const cellWidth = Math.max(cardWidth, maxX / cols);

        const cellHeight = Math.max(cardHeight, maxY / rows);

        const startX = (maxX - (cols * cellWidth)) / 2;

        // 应用当前层的随机垂直偏移

        const layerYOffset = layerOffsets[layer];

        const startY = (maxY - (rows * cellHeight)) / 2 + layerYOffset;



        for (let i = 0; i < layerCards; i++) {

            const row = Math.floor(i / maxCols);

            const col = i % maxCols;

            let baseX = startX + col * cellWidth + (cellWidth - cardWidth) / 2;

            let baseY = startY + row * cellHeight + (cellHeight - cardHeight) / 2;



            const offsetX = getRandomInt(-10, 10);

            const offsetY = getRandomInt(-10, 10);



            const x = Math.max(0, Math.min(maxX, baseX + offsetX));

            const y = Math.max(0, Math.min(maxY, baseY + offsetY));



            cardPositions.push({ x, y, z: layerZIndex });

        }

    }



    // 双重校验确保卡片数量正确

    if (cardPositions.length < cardCount) {

        for (let i = cardPositions.length; i < cardCount; i++) {

            const x = getRandomInt(0, maxX);

            const y = getRandomInt(0, maxY);

            cardPositions.push({ x, y, z: getRandomInt(1, layers) });

        }

    }

}



// 卡片遮挡状态

function updateCardMasks() {

    $('.card:not(.eliminate)').each(function () {

        const $card = $(this);

        const cardZ = parseInt($card.css('z-index')) || 0;

        const cardRect = $card[0].getBoundingClientRect();



        let isCovered = false;

        $('.card:not(.eliminate)').each(function () {

            const $otherCard = $(this);

            if ($otherCard[0] === $card[0]) return true;

            const otherZ = parseInt($otherCard.css('z-index')) || 0;



            if (otherZ > cardZ) {

                const otherRect = $otherCard[0].getBoundingClientRect();



                const hasOverlap = !(cardRect.right < otherRect.left ||

                    cardRect.left > otherRect.right ||

                    cardRect.bottom < otherRect.top ||

                    cardRect.top > otherRect.bottom);



                if (hasOverlap) {

                    isCovered = true;

                    return false;

                }

            }

        });



        const $mask = $card.find('.mask');

        if (isCovered) {

            $mask.show();

            $card.addClass('masked').css('pointer-events', 'none');

        } else {

            // 隐藏遮罩并启用点击

            $mask.hide();

            $card.removeClass('masked').css('pointer-events', 'auto');

        }

    });

}



function getLevelName(level) {

    const names = ['第一关', '第二关', '第三关', '第四关', '第五关', '第六关'];

    return names[level - 1] || '第一关';

}



// 按类型排序存储区的卡牌

function sortStoredCards() {

    const grouped = {};

    storedCards.forEach(card => {

        if (!grouped[card.type]) {

            grouped[card.type] = [];

        }

        grouped[card.type].push(card);

    });



    // 合并分组

    const sortedCards = [];

    Object.keys(grouped).forEach(type => {

        sortedCards.push(...grouped[type]);

    });



    // 更新存储区DOM位置

    const $items = $('.stored-card .item');

    $items.each(function () {

        $(this).children().not('i').remove();

    });



    sortedCards.forEach((card, index) => {

        $items.eq(index).append(card.element);

        card.position = index;

    });



    // 更新存储数组的顺序

    storedCards = sortedCards;

}



// 移动到存储区

function moveToStoredArea(card) {

    if (storedCards.length >= 7) {

        showFailPopup();

        return;

    }

    const cardType = card.data('type');

    const cardId = card.data('id');

    // 查找空白的item

    const emptyIndex = $('.stored-card .item').toArray().findIndex(item => {

        const $item = $(item);

        return $item.children().length === 1 && $item.children('i').length === 1;

    });



    if (emptyIndex === -1) {

        return;

    }



    // 查找是否有相同类型的卡片

    const sameTypeIndex = storedCards.findIndex(item => item.type === cardType);



    if (emptyIndex !== -1) {

        const animCard = card.clone();

        animCard.addClass('anim-card');

        animCard.css({

            position: 'fixed',

            zIndex: 1000,

            width: card.width() + 'px',

            height: card.height() + 'px'

        });

        $('body').append(animCard);



        // 获取起始位置

        const cardOffset = card.offset();

        animCard.css({

            left: cardOffset.left + 'px',

            top: cardOffset.top + 'px'

        });

        let targetItem;

        let targetIndex;



        if (sameTypeIndex !== -1 && emptyIndex > 0) {



            targetItem = $('.stored-card .item').eq(emptyIndex);

            targetIndex = emptyIndex;

        } else {

            targetItem = $('.stored-card .item').eq(emptyIndex);

            targetIndex = emptyIndex;

        }



        const targetOffset = targetItem.offset();



        // 执行动画

        gsap.to(animCard, {

            left: targetOffset.left,

            top: targetOffset.top,

            width: targetItem.width(),

            height: targetItem.height(),

            duration: 0.5,

            ease: "power2.out",

            onComplete: function () {

                const storedCard = card.clone();

                storedCard.css({

                    position: 'relative',

                    left: '0',

                    top: '0',

                    width: '100%',

                    height: '100%',

                    transform: 'none'

                });

                targetItem.append(storedCard);



                // 添加到存储数组

                storedCards.push({

                    type: cardType,

                    id: cardId,

                    element: storedCard,

                    position: targetIndex

                });

                sortStoredCards();



                // 移除动画卡片和原卡片

                animCard.remove();

                card.addClass('eliminate');



                setTimeout(() => {

                    card.remove();

                    // 更新剩余卡牌数

                    remainingCards--;

                    $('#card-count').text(remainingCards);

                    $('.leftover').text(`还剩${remainingCards}张牌`);



                    updateCardMasks();



                    // 等待点击音效播放完毕后再检查匹配和消除

                    if (audioState.enabled && audioState.soundElement) {

                        const checkAfterSound = () => {

                            checkForMatches().then(() => {

                                checkGameStatus();

                            });

                            audioState.soundElement.removeEventListener('ended', checkAfterSound);

                        };



                        if (audioState.soundElement.ended || audioState.soundElement.paused) {

                            checkForMatches().then(() => {

                                checkGameStatus();

                            });

                        } else {

                            audioState.soundElement.addEventListener('ended', checkAfterSound);

                        }

                    } else {

                        checkForMatches().then(() => {

                            checkGameStatus();

                        });

                    }

                }, 300);

            }

        });

    }

}



// 检查是否有匹配

function checkForMatches() {

    return new Promise(resolve => {

        const typeCount = {};



        // 计算每种类型的数量

        storedCards.forEach(card => {

            typeCount[card.type] = (typeCount[card.type] || 0) + 1;

        });



        // 检查是否有三种相同类型

        let hasMatch = false;

        for (const type in typeCount) {

            if (typeCount[type] >= 3) {

                hasMatch = true;

                // 收集需要删除的卡牌

                const toRemove = storedCards

                    .filter(card => card.type === type)

                    .slice(0, 3);



                // 播放消除音效

                const randomAudio = audioList[Math.floor(Math.random() * audioList.length)];

                playSound(randomAudio);



                // 删除逻辑

                const removePromises = toRemove.map(card => {

                    return new Promise(resolve => {

                        card.element.addClass('eliminate');

                        setTimeout(() => {

                            card.element.remove();

                            // 从存储数组中移除

                            const index = storedCards.indexOf(card);

                            if (index !== -1) {

                                storedCards.splice(index, 1);

                            }

                            resolve();

                        }, 500);

                    });

                });



                // 等待所有消除动画完成

                Promise.all(removePromises).then(() => {

                    // 更新进度

                    const progress = Math.round(((totalCards - remainingCards) / totalCards) * 100);

                    $('#match-progress').text(progress + '%');

                    sortStoredCards();

                    resolve();

                });



                break;

            }

        }



        if (!hasMatch) {

            resolve();

        }

    });

}



// 检查游戏状态

function checkGameStatus() {

    // 如果存储区已满且无法继续

    if (storedCards.length >= 7) {

        showFailPopup();

        return;

    }



    // 判断胜利条件

    if (remainingCards === 0) {

        if (currentLevel === 6) {

            showLastLevelPopup();

        } else {

            showSuccessPopup();

        }

    }

}



// 显示成功弹窗

function showSuccessPopup() {

    $('.success').css({

        'display': 'flex',

        'transform': 'translateY(0)'

    });

    pauseBgm();

}



// 显示失败弹窗

function showFailPopup() {

    $('.fail').css({

        'display': 'flex',

        'transform': 'translateY(0)'

    });

    pauseBgm();

}



// 显示最后一关弹窗

function showLastLevelPopup() {

    $('.last-level').css({

        'display': 'flex',

        'transform': 'translateY(0)'

    });

    pauseBgm();

}



// 同步卡片与容器项的尺寸

function syncCardSize() {

    const $firstItem = $('.container .item').first();

    if (!$firstItem.length) return;

    const itemWidth = $firstItem.width();

    const itemHeight = $firstItem.height();



    $('.card').css({

        width: itemWidth + 'px',

        height: itemHeight + 'px'

    });



    $('.card .img').css({

        width: '90%',

        height: '90%'

    });

}

syncCardSize();



$(window).on('resize', syncCardSize);

$('.container').on('DOMSubtreeModified', syncCardSize);



const originalAppend = $.fn.append;

$.fn.append = function () {

    const result = originalAppend.apply(this, arguments);

    if (this.hasClass('container') || this.hasClass('cards-box')) {

        syncCardSize();

    }

    return result;

};



// 背景音乐数据

const bgmList = [

    './audio/bgm01.mp3',

    './audio/bgm02.mp3',

    './audio/bgm03.mp3',

    './audio/bgm04.mp3'

];

let whatBgm = 0;



// 切换BGM按钮

$('.change-bgaudio').on('click', function () {

    whatBgm = (whatBgm + 1) % bgmList.length;

    $('.bg-audio').attr('src', bgmList[whatBgm]);

    audioState.bgmElement.volume = audioState.bgmVolume;

    $('.bg-audio')[0].play().catch(err => {

        console.log('BGM播放失败:', err);

    });

});



// 音频状态管理（默认关闭）

const audioState = {

    enabled: false,

    bgmElement: $('.bg-audio')[0],

    soundElement: $('.sound-effect')[0],

    bgmVolume: 0.3,

    soundVolume: 0.8

};



function initAudioVolume() {

    audioState.bgmElement.volume = audioState.bgmVolume;

    audioState.soundElement.volume = audioState.soundVolume;

}



// 页面加载时执行初始化

initAudioVolume();



// 播放音效函数

function playSound(src) {

    if (!audioState.enabled) return;



    audioState.soundElement.src = src;

    audioState.soundElement.currentTime = 0;

    audioState.soundElement.play().catch(err => {

        console.log('音效效播放失败:', err);

    });

}



// 播放背景音乐函数

function playBgm(src) {

    if (!audioState.enabled) return;



    if (!src) {

        src = bgmList[whatBgm];

    }

    audioState.bgmElement.src = src;

    audioState.bgmElement.currentTime = 0;

    audioState.bgmElement.volume = audioState.bgmVolume;

    audioState.bgmElement.play().catch(err => {

        console.log('背景音乐播放失败:', err);

    });

}



// 暂停背景音乐

function pauseBgm() {

    if (audioState.bgmElement) {

        audioState.bgmElement.pause();

    }

}



let isReordering = false;

let isFirstReorder = true;



// 重置重新排序按钮状态

function resetReorderButton() {

    isFirstReorder = true;

    $('.reorder').text('点击降低难度');

}



// 重新排序卡片函数

function reorderCards() {

    if (isReordering) return;



    const $cards = $('.cards-box .card:not(.eliminate)');

    if ($cards.length === 0) return;



    // 如果是首次点击，更改按钮文字

    const $reorderBtn = $('.reorder');

    if (isFirstReorder) {

        $reorderBtn.text('重新排序');

        isFirstReorder = false;

    }



    // 设置节流状态和按钮禁用

    isReordering = true;

    $reorderBtn.addClass('disabled').css({

        'opacity': '0.8',

        'cursor': 'not-allowed',

        'pointer-events': 'none'

    });



    // 隐藏所有卡片的图片

    $cards.find('.img').css('opacity', '0');



    // 获取当前所有卡片的信息

    const cardData = [];

    $cards.each(function () {

        const $card = $(this);

        cardData.push({

            element: $card,

            type: $card.data('type'),

            id: $card.data('id'),

            currentX: parseInt($card.css('left')),

            currentY: parseInt($card.css('top')),

            currentZ: parseInt($card.css('z-index'))

        });

    });



    // 重新生成位置

    const cardWidth = $('.stored-card .item').width();

    const cardHeight = $('.stored-card .item').height();

    generateCardPositions(cardData.length, cardWidth, cardHeight);



    // 随机打乱z-index顺序，确保层级真正随机化

    const shuffledZIndexes = cardPositions.map(pos => pos.z).sort(() => Math.random() - 0.5);

    cardPositions.forEach((pos, index) => {

        pos.z = shuffledZIndexes[index];

    });



    // 创建洗牌动画时间线

    const tl = gsap.timeline();

    const $cardsBox = $('.cards-box');

    const cardsBoxWidth = $cardsBox.width();

    const cardsBoxHeight = $cardsBox.height();



    // 计算中心位置

    const centerX = cardsBoxWidth / 2 - cardWidth / 2;

    const centerY = cardsBoxHeight / 2 - cardHeight / 2;



    // 所有卡片向中心聚集

    tl.to($cards, {

        left: centerX + 'px',

        top: centerY + 'px',

        rotation: 180,

        scale: 0.8,

        duration: 0.6,

        ease: "power2.inOut",
        stagger: 0.03

    })

        // 卡片散开到新位置

        .to($cards, {

            left: (index) => cardPositions[index].x + 'px',

            top: (index) => cardPositions[index].y + 'px',

            x: 0,

            y: 0,

            rotation: 0,

            scale: 1,

            duration: 0.8,

            ease: "back.out(1.7)",

            stagger: 0.04,

            onComplete: function () {

                // 动画完成后更新CSS属性和z-index

                $cards.each(function (index) {

                    const $card = $(this);

                    $card.css({

                        left: cardPositions[index].x + 'px',

                        top: cardPositions[index].y + 'px',

                        'z-index': cardPositions[index].z,

                        transform: 'none'

                    });

                });



                // 延迟更新遮罩状态

                setTimeout(() => {

                    updateCardMasks();



                    // 显示所有卡片的图片

                    $cards.find('.img').css('opacity', '1');



                    setTimeout(() => {

                        isReordering = false;

                        $reorderBtn.removeClass('disabled').css({

                            'opacity': '1',

                            'cursor': 'pointer',

                            'pointer-events': 'auto'

                        });

                    }, 200);

                }, 50);

            }

        });

}



// 初始化游戏

$(document).ready(function () {

    updateTime();

    setInterval(updateTime, 1000);



    // 初始化存储区域

    for (let i = 0; i < 7; i++) {

        $('.stored-card .container').append('<li class="item"><i></i></li>');

    }



    createCard(currentLevel);



    // 重新开始按钮

    $('.regame').on('click', function () {

        resetReorderButton();

        createCard(currentLevel);

        $('.challenge-results').hide();

    });



    // 音效开关

    $('.audio-switch').on('click', function () {

        audioState.enabled = !audioState.enabled;

        $('.audio-switch .audio-status').text(audioState.enabled ? '开启' : '关闭');



        if (audioState.enabled) {

            playBgm(bgmList[whatBgm]);

        } else {

            pauseBgm();

        }

    });



    // 再次挑战按钮

    $('.challenge-results .again').on('click', function () {

        resetReorderButton();

        createCard(currentLevel);

        $('.challenge-results').hide();

        if (audioState.enabled) {

            playBgm();

        }

    });



    // 下一关按钮

    $('.next').on('click', function () {

        currentLevel = Math.min(6, currentLevel + 1);

        resetReorderButton();

        createCard(currentLevel);

        $('.challenge-results').hide();

        if (audioState.enabled) {

            playBgm();

        }

    });



    // 最后一关的回第一关按钮

    $('.last-level .again').on('click', function () {

        currentLevel = 1;

        resetReorderButton();

        createCard(currentLevel);

        $('.challenge-results').hide();

        if (audioState.enabled) {

            playBgm();

        }

    });



    // 重新排序按钮

    $('.reorder').on('click', function () {

        reorderCards();

    });

});